package com.avic.rong.publishVideo.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.publishVideo.videoEdit.Adapter;
import com.avic.rong.publishVideo.videoEdit.Data;
import com.avic.rong.publishVideo.videoEdit.RangeBar;
import com.avic.rong.publishVideo.videoEdit.UIUtil;
import com.avic.rong.utils.ToastTools;
import com.esay.ffmtool.FfmpegTool;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static android.os.Environment.getExternalStorageDirectory;

public class EsayVideoEditActivity extends BaseActivity implements RangeBar.OnRangeBarChangeListener, View.OnClickListener {

    public static final String PATH = "path";
    private final int IMAGE_NUM = 10;//每一屏图片的数量
    private RecyclerView recyclerview;
    private RangeBar rangeBar;
    private FrameLayout fl_fram;
    private VideoView uVideoView;
    private String videoPath;
    private String parentPath;
    private long videoTime;
    private Adapter adapter;
    private LinearLayoutManager linearLayoutManager;
    private int imagCount = 0;//整个视频要解码图片的总数量
    FfmpegTool ffmpegTool;

    private int firstItem = 0;//recycleView当前显示的第一项
    private int lastItem = 0;//recycleView当前显示的最后一项
    private int leftThumbIndex = 0;//滑动条的左端
    private int rightThumbIndex = IMAGE_NUM;//滑动条的右端
    private int startTime, endTime = IMAGE_NUM;//裁剪的开始、结束时间
    private String videoResutlDir;//视频裁剪结果的存放目录
    private String videoResutl;
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    private Button btn_edit;
    private Button btn_edit_compress;

    //编辑后的视频
    private String EDIT_PATH = "edit_path";
    private ImageView userHeaderBackIcon;

    private TextView tv_cancel;
    private TextView tv_complete;
    private TextView tv_edit;
    private LinearLayout ll_edit;
    private LinearLayout ll_complete;
    private LinearLayout ll_root;
    private  File videoFile;


    // 获取视频从存储
    public static final int VIDEO_FROM_STORE = 4;

    private PublishVideoActivity publishVideoActivity;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_esay_video_edit;
    }

    @Override
    protected  void initView() {
        recyclerview = findViewById(R.id.recyclerview);
        rangeBar = findViewById(R.id.rangeBar);
        fl_fram = findViewById(R.id.fl_fram);
        uVideoView = findViewById(R.id.uVideoView);
        ll_root = findViewById(R.id.ll_root);


        tv_cancel = findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(this);
        tv_complete = findViewById(R.id.tv_complete);
        tv_complete.setOnClickListener(this);
        tv_edit = findViewById(R.id.tv_edit);
        tv_edit.setOnClickListener(this);
//        rl_common_head=findViewById(R.id.rl_common_head);
        ll_edit=findViewById(R.id.ll_edit);
        ll_complete=findViewById(R.id.ll_complete);

        tvTitle.setText("视频编辑");
        tvRight.setText("完成");

        ll_root.setVisibility(View.VISIBLE);
        ll_edit.setVisibility(View.VISIBLE);
        ll_complete.setVisibility(View.GONE);
        fl_fram.setVisibility(View.GONE);
//        btn_edit=findViewById(R.id.btn_edit);
//        btn_edit.setOnClickListener(this);
//        btn_edit_compress=findViewById(R.id.btn_edit_compress);
//        btn_edit_compress.setOnClickListener(this);

        videoPath = getIntent().getStringExtra(PATH);
        Log.i("onCreate", "videoPath:" + videoPath);
        if (!new File(videoPath).exists()) {
            Toast.makeText(this, "视频文件不存在", Toast.LENGTH_LONG).show();
            finish();
        }
        String str = "temp" + System.currentTimeMillis() / 1000;
        parentPath = getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "test" + File.separator + str + File.separator;
        videoResutlDir = getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "test" + File.separator + "clicp";
        File file = new File(parentPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        rangeBar.setmTickCount(IMAGE_NUM + 1);
        videoTime = UIUtil.getVideoDuration(videoPath);
        Log.i("onCreate", "videoTime:" + videoTime);
        ffmpegTool = FfmpegTool.getInstance(this);
        ffmpegTool.setImageDecodeing(new FfmpegTool.ImageDecodeing() {
            @Override
            public void sucessOne(String s, int i) {
                adapter.notifyItemRangeChanged(i, 1);
            }
        });

        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerview.setLayoutManager(linearLayoutManager);
        adapter = new Adapter(this, getDataList(videoTime));
        adapter.setParentPath(parentPath);
        adapter.setRotation(UIUtil.strToFloat(UIUtil.getVideoInf(videoPath)));
        recyclerview.setAdapter(adapter);
        recyclerview.addOnScrollListener(onScrollListener);
        rangeBar.setOnRangeBarChangeListener(this);//设置滑动条的监听
        uVideoView.setVideoPath(videoPath);
        uVideoView.start();


        initData();




    }

    @Override
    protected void addListener() {
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(videoPath))return;
                if (Build.VERSION.SDK_INT >= 23) {//6.0才用动态权限
                    initPermission();
                } else {
                    if (videoFile==null){
                        videoFile = new File(videoPath);
                    }
                    String videoSize = UIUtil.ReadVideoSize(videoFile);
                    videoSize=videoSize.replace("MB","");
                    if (Double.parseDouble(videoSize)>=100&&!TextUtils.isEmpty(videoSize)){
                        ToastTools.showToast(EsayVideoEditActivity.this,"发布视频最大为100MB，请重新上传");
                        finish();
                    }else {
                        videoCompressEdit(videoPath);
                    }
                }



            }
        });
    }

    /**
     * 第一次解码，先解码两屏的图片
     */
    private void initData() {
        File parent = new File(parentPath);
        if (!parent.exists()) {
            parent.mkdirs();
        }
//        Toast.makeText(this, "第一次解码中，先解码两屏的图片", Toast.LENGTH_SHORT).show();
        runImagDecodTask(0, 2 * IMAGE_NUM);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_complete:
                videoEdit();
                break;

            case R.id.tv_edit:
                ll_root.setVisibility(View.GONE);
                ll_edit.setVisibility(View.GONE);
                ll_complete.setVisibility(View.VISIBLE);
                fl_fram.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_cancel:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 视频压缩
     */
    private void videoCompressEdit(String videoPath) {
        File file = new File(videoPath);
        if (file.exists()) {
            Toast.makeText(this, "开始压缩，过程可能比较漫长", Toast.LENGTH_SHORT).show();
            showDialogTitle("正在压缩中...");
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    //压缩后视频的保存路径
                    String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                            + File.separator + "test" + File.separator + "compress";
                    File file1 = new File(path);
                    if (!file1.exists()) {
                        file1.mkdirs();
                    }
                    ffmpegTool.compressVideo(videoPath, path + File.separator, 3, new FfmpegTool.VideoResult() {
                        @Override
                        public void clipResult(int i, String s, String s1, boolean b, int i1) {
                            String result = "压缩完成";

                            if (!b) {
                                result = "压缩失败";
                            }
                            if (result.equals("压缩完成")) {
                                Intent intent = new Intent();
                                intent.putExtra(EDIT_PATH, s1);
                                setResult(RESULT_OK, intent);
                                finish();
                            }
                            Log.i("click2", "s:" + s);//压缩前的视频
                            Log.i("click2", "s1:" + s1);//压缩后的视频
                            Toast.makeText(EsayVideoEditActivity.this, result, Toast.LENGTH_SHORT).show();
                            dismissDialogTitle();
                        }
                    });
                }
            });
        } else {
            Toast.makeText(this, "未找到裁剪后的视频", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 裁剪
     */
    private void videoEdit() {
        uVideoView.stopPlayback();
        File file = new File(videoResutlDir);
        if (!file.exists()) {
            file.mkdirs();
        }
//        Toast.makeText(this, "开始裁剪视频", Toast.LENGTH_LONG).show();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                String video = videoResutlDir + File.separator + "clip" + System.currentTimeMillis() / 1000 + ".mp4";
                ffmpegTool.clipVideo(videoPath, video, startTime, endTime - startTime, 2, new FfmpegTool.VideoResult() {
                    @Override
                    public void clipResult(int i, String s, String s1, boolean b, int i1) {
                        Log.i("clipResult", "clipResult:" + s1);
                        String re = "裁剪视频完成";
                        if (!b) {
                            re = "裁剪视频失败";
                        }

                        videoResutl = s1;
                        if (re.equals("裁剪视频完成")) {
                            Intent intent = new Intent();
                            intent.putExtra(EDIT_PATH, s1);
                            setResult(RESULT_OK, intent);
                            finish();
//                            videoCompressEdit();
                        }
//                        Toast.makeText(EsayVideoEditActivity.this, re, Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }

    /**
     * 根据视频的时长，按秒分割成多个data先占一个位置
     *
     * @return
     */
    public List<Data> getDataList(long videoTime) {
        List<Data> dataList = new ArrayList<>();
        int seconds = (int) (videoTime / 1000);
        for (imagCount = 0; imagCount < seconds; imagCount++) {
            dataList.add(new Data(imagCount, "temp" + imagCount + ".jpg"));
        }
        return dataList;
    }

    /**
     * rangeBar 滑动改变时监听，重新计算时间
     *
     * @param rangeBar
     * @param leftThumbIndex
     * @param rightThumbIndex
     */
    @Override
    public void onIndexChangeListener(RangeBar rangeBar, int leftThumbIndex, int rightThumbIndex) {
        Log.i("onIndexChange", "leftThumbIndex:" + leftThumbIndex + "___rightThumbIndex:" + rightThumbIndex);
        this.leftThumbIndex = leftThumbIndex;
        this.rightThumbIndex = rightThumbIndex;
        calStartEndTime();
    }

    /**
     * 计算开始结束时间
     */
    private void calStartEndTime() {
        int duration = rightThumbIndex - leftThumbIndex;
        startTime = firstItem + leftThumbIndex;
        endTime = startTime + duration;
        //此时可能视频已经结束，若已结束重新start
        if (!uVideoView.isPlaying()) {
            uVideoView.start();
        }
        //把视频跳转到新选择的开始时间
        uVideoView.seekTo(startTime * 1000);
    }

    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            Log.i("onScrollStateChanged", "onScrollStateChanged :" + newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                firstItem = linearLayoutManager.findFirstVisibleItemPosition();
                lastItem = linearLayoutManager.findLastVisibleItemPosition();
                List<Data> dataList = adapter.getDataList();
                for (int i = firstItem; i <= lastItem; i++) {
                    if (!UIUtil.isFileExist(parentPath + dataList.get(i).getImageName())) {
                        Log.i("onScrollStateChanged", "not exist :" + i);
                        runImagDecodTask(i, lastItem - i + 1);
                        break;
                    }
                }
            }
            calStartEndTime();
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
        }
    };

    /**
     * 运行一个图片的解码任务
     *
     * @param start 解码开始的视频时间 秒
     * @param count 一共解析多少张
     */
    private void runImagDecodTask(final int start, final int count) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                ffmpegTool.decodToImageWithCall(videoPath, parentPath, start, count);
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {//获取到图片总的显示范围的大小后，设置每一个图片所占有的宽度
            adapter.setImagWidth(rangeBar.getMeasuredWidth() / IMAGE_NUM);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        uVideoView.pause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        uVideoView.stopPlayback();
        //最后不要忘了删除这个临时文件夹 parentPath
        //不然时间长了会在手机上生成大量不用的图片，该activity销毁后这个文件夹就用不到了
        //如果内存大，任性不删也可以
    }


    //申请三个权限，录音和文件读写、相机
    //1、首先声明一个数组permissions，将需要的权限都放在里面

    String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};
    //2、创建一个mPermissionList，逐个判断哪些权限未授予，未授予的权限存储到mPerrrmissionList中
    List<String> mPermissionList = new ArrayList<>();

    private final int mRequestCode = 100;//权限请求码

    //权限判断和申请
    private void initPermission() {

        mPermissionList.clear();//清空没有通过的权限

        //逐个判断你要的权限是否已经通过
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);//添加还未授予的权限
            }
        }

        //申请权限
        if (mPermissionList.size() > 0) {//有权限没有通过，需要申请
            ActivityCompat.requestPermissions(this, permissions, mRequestCode);
        } else {
            //说明权限都已经通过，可以做你想做的事情去
            if (videoFile==null){
                videoFile = new File(videoPath);
            }
            String videoSize = UIUtil.ReadVideoSize(videoFile);
            videoSize=videoSize.replace("MB","");
            if (Double.parseDouble(videoSize)>=100&&!TextUtils.isEmpty(videoSize)){
                ToastTools.showToast(EsayVideoEditActivity.this,"发布视频最大为100MB，请重新上传");
                finish();
            }else {
                videoCompressEdit(videoPath);
            }
        }
    }


}
